package org.opencare.ndwc.persistence;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.opencare.ndwc.model.EventType;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
public class JpaEventTypeDao implements EventTypeDao {

	@PersistenceContext
    private EntityManager em;

	@Override
	public EventType find(Long id) throws DataAccessException {
		// TODO Auto-generated method stub
		return em.find(EventType.class, id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<EventType> findAll() throws DataAccessException {
		// TODO Auto-generated method stub
		
		Query ql = em.createQuery("select eventType from EventType eventType");
		List<EventType> result = ql.getResultList();
		
		return result;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public EventType findEventTypeByTypeName(String typeName)
			throws DataAccessException {
		// TODO Auto-generated method stub
		
		Query ql = em.createQuery("select eventType from EventType eventType where eventType.name = :name");
		ql.setParameter("name", typeName);
		
		EventType result = (EventType) ql.getSingleResult();
				
		return result;
	}
	
	@Transactional
	@Override
	public void save(EventType eventType) throws DataAccessException {
		// TODO Auto-generated method stub
		
		if(eventType.getId() == null){
			em.persist(eventType);
		}else{
			em.merge(eventType);
		}
	}

	@Transactional
	@Override
	public void removeAll() throws DataAccessException {
		// TODO Auto-generated method stub
		em.createQuery ("delete from EventType").executeUpdate();
	}

	@Transactional
	@Override
	public void remove(Long id) throws DataAccessException {
		// TODO Auto-generated method stub
		Query q1 = em.createQuery("delete from EventType e where e.id = :id");
		q1.setParameter("id", id);
		q1.executeUpdate();		
	}
	
	@Override
	public Long countEventType() throws DataAccessException {
		// TODO Auto-generated method stub
		
		Query ql = em.createQuery("select count(e) from EventType e");
		Long result = (Long) ql.getSingleResult();
				
		return result;
	}



}
